#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
作业模型
"""

from datetime import datetime
from sqlalchemy import Column, Integer, String, DateTime, Text, ForeignKey, Boolean, Float
from sqlalchemy.orm import relationship
from .base import Base

class Assignment(Base):
    """作业模型"""
    __tablename__ = 'assignments'
    
    id = Column(Integer, primary_key=True, autoincrement=True)
    title = Column(String(200), nullable=False, comment='作业标题')
    description = Column(Text, comment='作业描述')
    class_id = Column(Integer, ForeignKey('classes.id'), nullable=False, comment='班级ID')
    problem_ids = Column(Text, comment='关联的题目ID列表，JSON格式')
    due_date = Column(DateTime, nullable=False, comment='截止时间')
    total_score = Column(Float, default=100.0, comment='总分')
    status = Column(String(20), default='active', comment='作业状态：active/expired/completed')
    created_at = Column(DateTime, default=datetime.now, comment='创建时间')
    updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')
    
    # 关联关系
    class_obj = relationship('Class', back_populates='assignments')
    submissions = relationship('AssignmentSubmission', back_populates='assignment', cascade='all, delete-orphan')
    
    def __repr__(self):
        return f'<Assignment {self.title}>'
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'title': self.title,
            'description': self.description,
            'class_id': self.class_id,
            'class_name': self.class_obj.name if self.class_obj else None,
            'problem_ids': self.problem_ids,
            'due_date': self.due_date.isoformat() if self.due_date else None,
            'total_score': self.total_score,
            'status': self.status,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None,
            'submission_count': len(self.submissions)
        }
    
    def is_expired(self):
        """检查作业是否已过期"""
        return datetime.now() > self.due_date
    
    def get_submission_stats(self):
        """获取提交统计信息"""
        total_students = len(self.class_obj.students) if self.class_obj else 0
        submitted_count = len(self.submissions)
        return {
            'total_students': total_students,
            'submitted_count': submitted_count,
            'submission_rate': (submitted_count / total_students * 100) if total_students > 0 else 0
        }

class AssignmentSubmission(Base):
    """作业提交模型"""
    __tablename__ = 'assignment_submissions'
    
    id = Column(Integer, primary_key=True, autoincrement=True)
    assignment_id = Column(Integer, ForeignKey('assignments.id'), nullable=False, comment='作业ID')
    student_id = Column(Integer, ForeignKey('users.id'), nullable=False, comment='学生ID')
    problem_id = Column(Integer, ForeignKey('problems.id'), nullable=False, comment='题目ID')
    code = Column(Text, comment='提交的代码')
    language = Column(String(20), default='python', comment='编程语言')
    status = Column(String(20), default='pending', comment='提交状态：pending/running/accepted/wrong_answer/time_limit/memory_limit/compile_error')
    score = Column(Float, default=0.0, comment='得分')
    execution_time = Column(Float, comment='执行时间(ms)')
    memory_usage = Column(Float, comment='内存使用(MB)')
    error_message = Column(Text, comment='错误信息')
    submitted_at = Column(DateTime, default=datetime.now, comment='提交时间')
    graded_at = Column(DateTime, comment='批改时间')
    graded_by = Column(Integer, ForeignKey('users.id'), comment='批改教师ID')
    feedback = Column(Text, comment='教师反馈')
    
    # 关联关系
    assignment = relationship('Assignment', back_populates='submissions')
    student = relationship('User', foreign_keys=[student_id])
    problem = relationship('Problem')
    grader = relationship('User', foreign_keys=[graded_by])
    
    def __repr__(self):
        return f'<AssignmentSubmission {self.assignment_id}-{self.student_id}-{self.problem_id}>'
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'assignment_id': self.assignment_id,
            'assignment_title': self.assignment.title if self.assignment else None,
            'student_id': self.student_id,
            'student_name': self.student.name if self.student else None,
            'problem_id': self.problem_id,
            'problem_title': self.problem.title if self.problem else None,
            'code': self.code,
            'language': self.language,
            'status': self.status,
            'score': self.score,
            'execution_time': self.execution_time,
            'memory_usage': self.memory_usage,
            'error_message': self.error_message,
            'submitted_at': self.submitted_at.isoformat() if self.submitted_at else None,
            'graded_at': self.graded_at.isoformat() if self.graded_at else None,
            'graded_by': self.graded_by,
            'grader_name': self.grader.name if self.grader else None,
            'feedback': self.feedback
        }
    
    def is_late(self):
        """检查是否逾期提交"""
        if self.assignment and self.assignment.due_date:
            return self.submitted_at > self.assignment.due_date
        return False
